﻿using FD.RemoteAssistant.Core;
using FD.RemoteAssistant.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Castle.Core.Internal;
using FDRemoteAssistant2.Models;

namespace FDRemoteAssistant2.Manager
{
    /*
     CreatedOn: 2018-05-15
     CreatedBy: Jackie Lee(天宇遊龍)
         */
    public class FDHelper
    {
        private FDHelper() { _serializer = RuntimeContext.Current.Container.Resolve<ISerializer>(); }

        /// <summary>
        /// 编辑数据变化时通知
        /// </summary>
        public event EventHandler<MenuDataChangedArgs> MenuDataChanged;

        static FDHelper()
        {
            Current = new FDHelper();
        }

        public static FDHelper Current { get; }

        public RemoteConfig RemoteConfig { get; private set; }

        private static readonly string configName = "RAConfig.json";

        private readonly ISerializer _serializer;

        /// <summary>
        /// 通知数据变化
        /// </summary>
        /// <param name="remoteSetting"></param>
        /// <param name="changeType"></param>
        public void RemoteConfigChange(IRemoteSetting remoteSetting, ChangeType changeType, string oldMenuName = "")
        {
            MenuDataChanged?.Invoke(this, new MenuDataChangedArgs(remoteSetting, changeType, oldMenuName));
        }

        public void Save()
        {
            if (RemoteConfig == null)
            {
                RemoteConfig = new RemoteConfig
                {
                    Name = "Default config",
                    RemoteSettings = new List<RemoteSetting>()
                };
            }
            AddRemoteSettings();

            using (var fs = new FileStream(configName, FileMode.Create))
            {
                var sw = new StreamWriter(fs, Encoding.UTF8);
                var res = _serializer.Serialize(RemoteConfig);
                sw.Write(res);
                sw.Flush();
            }
        }

        public void Load()
        {
            if (!File.Exists(configName))
            {
                RemoteConfig = new RemoteConfig
                {
                    Name = "Default config",
                    RemoteSettings = new List<RemoteSetting>()
                };
                AddRemoteSettings();

                return;
            }

            RemoteConfig = _serializer.Deserialize<RemoteConfig>(File.ReadAllText(configName, Encoding.UTF8));
            RuntimeContext.Current.RemoteSettings.AddRange(RemoteConfig.RemoteSettings);
        }

        private void AddRemoteSettings()
        {
            RemoteConfig.RemoteSettings.Clear();
            RuntimeContext.Current.RemoteSettings.ForEach(a =>
            {
                RemoteConfig.RemoteSettings.Add((RemoteSetting)a);
            });
        }

        public string GetRemoteName(IRemoteSetting remoteSetting, bool bTip = false)
        {
            var tip = bTip ? (remoteSetting.Group.IsNullOrEmpty() ? "" : $"{remoteSetting.Group}:") : "";
            return $"{tip}{remoteSetting.UserName}-{remoteSetting.Server}";
        }

        public string GetDisplayText(IRemoteSetting remoteSetting)
        {
            if (!remoteSetting.Name.IsNullOrEmpty())
            {
                return remoteSetting.Name;
            }

            return GetRemoteName(remoteSetting);
        }

        public string GetServer(string remoteName)
        {
            if (remoteName.IsNullOrEmpty())
            {
                return string.Empty;
            }

            var items = remoteName.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
            if (items.Length == 2)
            {
                return items[1];
            }

            return string.Empty;
        }
    }
}
